import os
import json
import base64
from pathlib import Path
from cryptography.fernet import Fernet


def generate_key():
    """生成 Fernet 密钥（44 字节 base64 编码）"""
    return Fernet.generate_key()


def save_key(key, file_path):
    """保存密钥到文件"""
    with open(file_path, 'wb') as f:
        f.write(key)


def load_key(file_path):
    """加载并自动修复密钥格式"""
    with open(file_path, 'rb') as f:
        key_data = f.read().strip()

    # 修复 32 字节原始密钥（旧版本错误）
    if len(key_data) == 32:
        print("⚠️ 检测到原始二进制密钥，正在转换...")
        key_data = base64.urlsafe_b64encode(key_data)
        with open(file_path, 'wb') as f:
            f.write(key_data)
        print("✅ 密钥已转换为 base64 格式")

    # 验证格式
    if len(key_data) != 44:
        raise ValueError(f"密钥格式错误: 期望 44 字节，实际 {len(key_data)} 字节")

    return key_data


def encrypt_data(data: str, key: bytes) -> bytes:
    """加密字符串数据"""
    fernet = Fernet(key)
    return fernet.encrypt(data.encode('utf-8'))


def decrypt_data(encrypted_data: bytes, key: bytes) -> str:
    """解密为字符串"""
    fernet = Fernet(key)
    return fernet.decrypt(encrypted_data).decode('utf-8')


def encrypt_to_txt(plain_text: str, file_path: Path, key: bytes):
    """加密并保存到文件"""
    encrypted_data = encrypt_data(plain_text, key)
    file_path.write_bytes(encrypted_data)


def decrypt_from_txt(file_path: Path, key: bytes) -> str:
    """从文件解密"""
    encrypted_data = file_path.read_bytes()
    return decrypt_data(encrypted_data, key)